<template>
  <div class="address_setting">
    <!-- 我的地址标题 -->
    <div class="address_nav">
      <img src="../../assets/images/jiantou_left.png" alt="" class="back-arrow" @click="goback">
      <div class="title">我的地址</div>
    </div>

    <!-- 我的地址主体 -->
    <div class="address_body">
      <div v-for="(address, index) in addresses" :key="index" class="address-item">
        <img src="../../assets/images/quaddress.png" alt="" v-if="address.addressType===2" class="body_img">
        <img src="../../assets/images/shouaddress.png" alt="" v-else-if="address.addressType===1" class="body_img">
        <span> {{ address.address }}</span>
        <div class="btns">
        <img src="../../assets/images/xiugai.png" alt="" @click="editAddress(index)">
        <img src="../../assets/images/shanchu2.png" alt="" @click="handledeleteAddress(index)">
        </div>
      </div>
    </div>

    <!-- 新增地址按钮 -->
    <div class="address_add_button">
      <button class="addbtn" @click="showAddAddress = true">+新增地址</button>
    </div>
    
    <!-- 修改或添加地址弹窗 -->
    <div v-if="showAddAddress" class="overlay">
      <div class="overlay-content">
        <h3>{{ isEditing ? '修改地址' : '添加地址' }}</h3>
        <input v-model="newAddress" placeholder="请输入地址" class="cin">
        <div class="radio-group">
          <label>
            <input type="radio" v-model="addressType" value="2">
            取
          </label>
          <label>
            <input type="radio" v-model="addressType" value="1">
            收
          </label>
        </div>
        <div class="twobtn">
          <button @click="savebtn">{{ isEditing ? '保存' : '添加' }}</button>
          <button @click="cancelbtn">取消</button>
        </div>
        
      </div>
    </div>
  
  </div>
</template>
<script setup lang="ts">
import {ref,onMounted} from "vue"
import { useRouter } from "vue-router";
import { addAddress, updateAddress,deleteAddress ,getAddresses} from "../../api/Address/index";

const router = useRouter();
const showAddAddress = ref(false);//控制弹窗
const newAddress = ref("");//地址
const addressType = ref(2);//地址类型
const addresses = ref<{ addId:number; userId:number; address: string; addressType: number }[]>([]);//地址列表
const isEditing = ref(false);//是否编辑
const addId = ref(0);//地址id
const userId = ref(0);//用户id
const editingIndex = ref<number | null>(null);//编辑索引

//从本地存储中获取用户信息
const storedUser = localStorage.getItem("user");
if (storedUser) {
  const user = JSON.parse(storedUser).user; // 解析用户信息
  userId.value = user.userId; // 提取用户 ID
}

// 返回我的页面
const goback = () => {
  router.go(-1)
}

// 保存地址
const savebtn = async () => {
  if (newAddress.value && addressType.value) {
    try {
      const requestDataadd = {
        // addId: addId.value,
        userId: userId.value,
        address: newAddress.value,
        addressType: Number(addressType.value)
      };
      const requestDataupdate = {
        addId: addId.value,
        userId: userId.value,
        address: newAddress.value,
        addressType: Number(addressType.value)
      };
      console.log("请求数据:", requestDataupdate); // 打印请求数据
      if (isEditing.value && editingIndex.value !== null) {
        // 更新地址
        await updateAddress(requestDataupdate);
        addresses.value[editingIndex.value] = { ...requestDataupdate };
         // 更新本地存储中的用户信息
         const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const user = JSON.parse(storedUser).user;
          user.addressArray = addresses.value;
          localStorage.setItem('user', JSON.stringify({ user }));
        }
        loadAddresses();
      } else {
        // 新增地址
        await addAddress(requestDataadd);
        addresses.value.push({ ...requestDataadd });
        // 更新本地存储中的用户信息
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const user = JSON.parse(storedUser).user;
          user.addressArray = addresses.value;
          localStorage.setItem('user', JSON.stringify({ user }));
        }
        loadAddresses();
      }
      localStorage.setItem('addressArray', JSON.stringify(addresses.value));
      resetForm();
    } catch (error) {
      console.error("保存地址失败:", error);
    }
  }
};

// 修改地址
const editAddress = (index: number) => {
  const address = addresses.value[index];
  newAddress.value = address.address;
  addressType.value = address.addressType;
  addId.value = address.addId;
  isEditing.value = true;
  editingIndex.value = index;
  showAddAddress.value = true;
};

// 取消按钮
const cancelbtn = () => {
  resetForm();
};

// 删除地址
const handledeleteAddress = async (index: number) => {
  try {
    const address = addresses.value[index];
    await deleteAddress(address.addId);
    addresses.value.splice(index, 1);
     // 更新本地存储中的用户信息
     const storedUser = localStorage.getItem('user');
        if (storedUser) {
          const user = JSON.parse(storedUser).user;
          user.addressArray = addresses.value;
          localStorage.setItem('user', JSON.stringify({ user }));
        }
  } catch (error) {
    console.error("删除地址失败:", error);
  }
};

// 重置表单
const resetForm = () => {
  newAddress.value = "";
  addressType.value = 2;
  isEditing.value = false;
  editingIndex.value = null;
  showAddAddress.value = false;
};

// 加载地址列表
const loadAddresses = async () => {
  try {
    const response = await getAddresses(userId.value);
    console.log("响应数据:", response.data); // 打印响应数据
    addresses.value = response.data.data;
    console.log("地址列表:", addresses.value); // 打印地址列表
    localStorage.setItem('addressArray', JSON.stringify(addresses.value));
  } catch (error) {
    console.error("加载地址失败:", error);
  }
};

onMounted(() => {
  loadAddresses();
});

</script>
<style lang="less" scoped>

.address_nav {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  height: 50px; 
  // border-bottom: 1px solid #ddd; 
}

.back-arrow {
  position: absolute;
  left: 10px; 
  width: 34px; 
  height: 34px; 
  margin-top: 10px;
}

.title {
  font-size: 18px; 
  text-align: center;
  margin-top: 10px;
}
.address_add_button{
  background-color: #FFFFFF;
  width: 430px;
  height: 81px;
  position: fixed;
  bottom: 0px; 
   padding-top: 20px;
}

.addbtn{
  width: 397px;
  height: 46px;
  background-color:rgba(252, 30, 9, 0.8);
  color: #FFFFFF;
  position: absolute;
  left: 50%; 
  transform: translateX(-50%); 
  border-radius: 34px;
  border: none;
  cursor: pointer;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.overlay-content {
  width: 326px;
  height: 193px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
}

.overlay-content h3 {
  margin-bottom: 20px;
}

.overlay-content .cin {
  width: 257px;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.radio-group {
  width: 203px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  margin-bottom: 20px;
 
}

.radio-group label {
  font-size: 16px;
  padding: 10px;
}

.twobtn{
  margin-top: 20px;
}

.overlay-content button {
  padding: 10px 30px;
  margin: 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.overlay-content button:first-of-type {
  background-color: #4095E5;
  color: #FFFFFF;
}

.overlay-content button:last-of-type {
  background-color: rgba(252, 30, 9, 0.8);
  color:#FFFFFF
}

.address_body {
  padding: 20px;
}

.body_img{
  height: 24px;
  margin-left: 27px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 30px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fff;
  max-width: 600px; /* 设置最大宽度 */
  height: 74px; /* 设置高度 */
}

.btns img{
  width: 24px;
  margin:0 5px;
}
</style>
